<?php

class ArticleController extends Controller
{
    public $layout = 'main';
    public $defaultAction = 'menu';

    private $_model;

    /**
     * @return array action filters
     */
    public function filters()
    {
        return CMap::mergeArray(parent::filters(),array(
            'accessControl', // perform access control for CRUD operations
        ));
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('menu','list','view','admin','delete','update','create','index','post', 'delpost'),
                'users'=>UserModule::getAdmins(),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }
    /**
     * Manages all models.
     */
    public function actionMenu()
    {
        $cid=Yii::app()->request->getParam('cid', 0);

        Yii::app()->getComponent('bootstrap');
        $article=Cate::model()->with('items')->findAll('`t`.`pid`=0 AND `t`.`type`=0 AND `items`.`type`=0 ');
        $this->render('menu',array(
            'dataProvider'=>array('data'=>$article, 'cid'=>$cid),
        ));
    }

    public function actionList(){

        $cid=Yii::app()->request->getParam('cid', 0);              //子类
        $pid=Yii::app()->request->getParam('pid', 0);              //父类
        $audit=Yii::app()->request->getParam('audit', 0);         //是否通过审核(0没有审核，1通过审核，-1没有通过审核)
        $enabled=Yii::app()->request->getParam('enable', 0);      //是否发布(后续增加回收站机制)

//        $criteria=new CDbCriteria;
//		$criteria->condition='status=1';
//		$criteria->order='pos ASC';
//        $dataProvider=new CActiveDataProvider('Article',array(
//		    'criteria'=>$criteria,
//            'pagination'=>array(
//                'pageSize'=>10,
//            ),
//        ));

//        $this->render('list',array(
//            'dataProvider'=>$dataProvider,
//        ));
        $model=new Article('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Article']))
            $model->attributes=$_GET['Article'];

        $this->render('list',array(
            'model'=>$model,
        ));
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new Article;
//        Yii::app()->getComponent('bootstrap');

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Article']))
        {
            $model->attributes=$_POST['Article'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->aid));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Article']))
        {
            $model->attributes=$_POST['Article'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->aid));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $criteria=new CDbCriteria;
        $criteria->condition='type=3';
        $dataProvider=new CActiveDataProvider('Article',array('criteria'=>$criteria));

        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }



    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new Article('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Article']))
            $model->attributes=$_GET['Article'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model=Article::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionPost()
    {
        $model=new Article;

        $aid=Yii::app()->request->getParam('aid', 0);
        $article=Article::model()->findByPk($aid);
        if(isset($article->aid)){
            $model=$article;
            $model->isNewRecord=false;
        }

//        Yii::app()->getComponent('bootstrap');

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Article']))
        {
            $model->attributes=$_POST['Article'];
            $model->uid=Yii::app()->user->id;
            $model->cid=0;
            $model->audit=0;
            $model->grade=0;
            $model->createtime=date("Y-m-d H:i:s");
            $model->updatetime='0000-00-00 00:00:00';
            $model->excerpt=$model->title;
            $model->enabled=0;
            $model->sort=0;
            $model->type=3;
            $model->clicknumber=0;

            if($model->isNewRecord==true){
                if($model->find('title=:title AND excerpt=:title',array(':title'=>$model->title))){
                    throw new CHttpException(400,'已经存在此内部页面');
                }
                if($model->save())
                    $this->render('//site/info',array(
                        'msg'=>'内部页面保存成功',
                        'direct'=>$this->createUrl('index'),
                    ));
            }else{
                if($model->update())
                    $this->render('//site/info',array(
                        'msg'=>'内部页面更新成功',
                        'direct'=>$this->createUrl('index'),
                    ));
            }


            return;
        }

        $this->render('post',array(
            'model'=>$model,
        ));
    }


    public function actionDelpost()
    {
        $aid=Yii::app()->request->getParam('aid', 0);
        $aid=intval($aid);
        $article=$this->loadModel($aid);
        if(!empty($article))
        {
            if($article->type==3 && $article->enabled==0){
                $article->delete();
                $this->render('//site/info',array(
                    'msg'=>'内部页面删除成功',
                    'direct'=>$this->createUrl('index'),
                ));
            }else{
                throw new CHttpException(400,'此文章无法删除.');
            }
        }
        else
            throw new CHttpException(400,'请输入正确参数.');
    }

}